(function($){
	var filter_studio_clouds = function(id){
		$.getJSON("/filter_clouds/", {'id': id}, function(data){
			var html = "<option value=''>---------</option>";
			$.each(data.res, function(k, v){
				if(v.id == $("#id_studio_clouds").val()){
					html += "<option selected='selected' value='" + v.id + "'>" + v.name + "</option>";
				}else{
					html += "<option value='" + v.id + "'>" + v.name + "</option>";
				}
			});
			$("#id_studio_clouds").html(html);
		});
	}
	
	var filter_studios = function(id){
		$.getJSON("/filter_studios/", {'id': id}, function(data){
			var html = "<option value=''>---------</option>";
			$.each(data.res, function(k, v){
				if(v.id == $("#id_studio").val()){
					html += "<option selected='selected' value='" + v.id + "'>" + v.name + "</option>";
				}else{
					html += "<option value='" + v.id + "'>" + v.name + "</option>";
				}
			});
			$("#id_studio").html(html);
		});
	}
	
	var filter_pjms = function(id){
		$.getJSON("/filter_pjms/", {'id': id}, function(data){
			var html = "<option value=''>---------</option>";
			$.each(data.res, function(k, v){
				if(v.id == $("#id_assign_pjm").val()){
					html += "<option selected='selected' value='" + v.id + "'>" + v.name + "</option>";
				}else{
					html += "<option value='" + v.id + "'>" + v.name + "</option>";
				}
			});
			$("#id_assign_pjm").html(html);
		});
	}
	
	$(document).ready(function(){
		$("#id_issued_by").after("\
	<input class='vTextField' id='id_issued_by_text' name='issued_by_text' type='text' style='display:none'>\
		");

		if($("#id_issued_by").val() == 'O'){
			$("#id_issued_by_text").css('display', 'inline-block');
		}else{
			$("#id_issued_by_text").css('display', 'none');
		}
		
		filter_studio_clouds($("#id_to").val());
		filter_studios($("#id_studio_clouds").val());
		filter_pjms($("#id_assign_team").val());
		
		$("#id_issued_by").change(function(e){
			if(e.target.value == 'O'){
				$("#id_issued_by_text").css('display', 'inline-block');
			}else{
				$("#id_issued_by_text").css('display', 'none');
				$("#id_issued_by_text").val('');
			}
		});
		
		$("#id_to").change(function(e){
			filter_studio_clouds(e.target.value);
			filter_studios();
		});
		$("#id_studio_clouds").change(function(e){
			filter_studios(e.target.value);
		});
		$("#id_assign_team").change(function(e){
			filter_pjms(e.target.value);
		});

	});
})(django.jQuery);